import json
import base64
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.tiia.v20190529 import tiia_client, models

import sys 
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())


def image_tagging(image_path):
    """
        输入图片路径，调用api
        返回图片的类别和一二级标签字符串
        例如： "文本-卡证文档-其他"
    """
 

    with open(image_path, "rb") as bin_data:
        image_data = bin_data.read()
    image_base64 = base64.b64encode(image_data).decode("utf-8")  # 使用图片的base64编码

    labels = [] 
    try:
        cred = credential.Credential("AKIDkRr1uWrviEdngIdhV2HGzRbU6RWKtBCw", "WljQr1uXtxkGVTAaiaBUWHlxsWtznKAk")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "tiia.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = tiia_client.TiiaClient(cred, "ap-beijing", clientProfile)

        req = models.DetectLabelRequest()
        params = {"ImageBase64":image_base64, "Scenes": ["WEB", "CAMERA", "ALBUM"]}
        req.from_json_string(json.dumps(params))

        resp = client.DetectLabel(req)
        result  = json.loads(resp.to_json_string())

        labels.append(result['Labels'][0]['Name'])
        labels.append(result['Labels'][0]['FirstCategory'])
        labels.append(result['Labels'][0]['SecondCategory'])
       

    except TencentCloudSDKException as err:
        return " "

    return '##'.join(labels)